﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace SwormTests.Misc
{
    public class transactions : TestBase
    {
        public transactions(DbToTest type) : base(type) { }

        class my_table
        {
            public string str1 { get; set; }
        }

        [Test]
        public void can_commit_transaction()
        {
            using (var trx = DB.BeginTransaction())
            {
                Assert.AreEqual(1, DB.TransactionDepth);

                var item = new my_table() { str1 = "asdf" };
                DB.Insert(item);

                trx.Commit();
                Assert.AreEqual(0, DB.TransactionDepth);
            }

            Assert.AreEqual(1, DB.Query.Simple<my_table>().List().Count);
        }

        [Test]
        public void can_rollback_transaction()
        {
            using (var trx = DB.BeginTransaction())
            {
                Assert.AreEqual(1, DB.TransactionDepth);

                var item = new my_table() { str1 = "asdf" };
                DB.Insert(item);

                trx.Rollback();
                Assert.AreEqual(0, DB.TransactionDepth);
            }

            Assert.AreEqual(0, DB.Query.Simple<my_table>().List().Count);
        }

        [Test]
        public void rolls_back_on_Dispose()
        {
            using (var trx = DB.BeginTransaction())
            {
                Assert.AreEqual(1, DB.TransactionDepth);

                var item = new my_table() { str1 = "asdf" };
                DB.Insert(item);

                // don't commit or rollback
            }

            Assert.AreEqual(0, DB.TransactionDepth);
            Assert.AreEqual(0, DB.Query.Simple<my_table>().List().Count);
        }

        [Test]
        public void rolls_back_on_exceptional_Dispose()
        {
            try
            {
                using (var trx = DB.BeginTransaction())
                {
                    Assert.AreEqual(1, DB.TransactionDepth);

                    var item = new my_table() { str1 = "asdf" };
                    DB.Insert(item);

                    throw new Exception("ERROR");
                }
            }
            catch(Exception ex)
            {
                Assert.AreEqual("ERROR", ex.Message);
            }

            Assert.AreEqual(0, DB.TransactionDepth);
            Assert.AreEqual(0, DB.Query.Simple<my_table>().List().Count);
        }
    }
}
